package com.hl.toolkit.server.bdpay;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class O2o_CodePayServlet { 
 
 	private ServletConfig scon = null;
	
	 
	
 

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	/**
	 *接收o2o_codepay.html页面的post请求
	 * 
	 */
	public String doPost(HttpServletRequest request, HttpServletResponse response,String order_no,String order_create_time)
			throws ServletException, IOException {
		
		String resultStr="";
		 /**
         * 1、设置编码
         */
		request.setCharacterEncoding("gbk");
		response.setCharacterEncoding("gbk");
		response.setContentType("text/html;charset=gbk");  
		response.setHeader("content-type","text/html;charset=gbk");
 		//打印日志
 
		/**
		 * 2、获取 web.xml内的常量值
	     */
		
		 //商品分类号
	    String  service_code= "service_code=1";
	    //商户号
	    String sp_no="sp_no="+BaiduConfig.spNo;
	    //交易的超时时间,当前时间加2天
	    Calendar   c   =   Calendar.getInstance(); 
	    c.add(Calendar.DAY_OF_MONTH, 2);  
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");  
        String mDateTime=formatter.format(c.getTime());  
 	    String strExpire=mDateTime.substring(0, 14);//
	    String expire_time= "expire_time=" +strExpire;
	    //订单创建时间
	    //订单号
	      order_create_time="order_create_time=" +order_create_time;
	      order_no="order_no="+order_no;
	    //实体商户名店号
	 //   String mno="mno="+request.getParameter("mno");
		//实体商户门店名称
	  // String mname ="mname=34000000011234567890" ;
	  // String mname1="mname="+URLEncoder.encode(mname,"gbk");
		//实体终端名称
//	  String tno="tno=12345678";
		//付款码
		String pay_code="pay_code="+request.getParameter("pay_code");
	    //币种
	    String currency="currency=1";
	    //编码
	    String input_charset="input_charset=1";
	    
 	    //版本
	    String version="version=2";
	    //加密方式md5或者hash
	    String sign_method="sign_method=1";
	    //提交地址
	    String BFB_PAY_DIRECT_O2O_PAY_URL=BaiduConfig.BaiduAddressScann;
	    //商品名称
	    String tempgoods_name=request.getParameter("goods_name");
	    String goods_name ="goods_name="+tempgoods_name;
	    String goods_name1="goods_name="+ URLEncoder.encode(request.getParameter("goods_name"),"gbk");
	    //商品描述
	//    String tempgoods_desc=request.getParameter("goods_desc");
	  //  String goods_desc ="goods_desc="+tempgoods_desc;
	   // String goods_desc1= "goods_desc="+URLEncoder.encode(request.getParameter("goods_desc"),"gbk");
	
 	    //String goods_category ="goods_category=1";
	//    String goods_category1= "goods_category="+URLEncoder.encode(goods_category,"gbk");

	    
	    //商品在商户网站上的URL
	    String goods_url ="goods_url=http://www.baidu.com";
	    String goods_url1="goods_url="+URLEncoder.encode("http://www.baidu.com","gbk");
	    //总金额
	    String total_amount ="total_amount="+request.getParameter("total_amount");
	   //后台通知地址 
        // String return_url ="return_url="+BaiduConfig.applicationNotiyReturnUrl;
 	  //  String return_url1="return_url="+URLEncoder.encode(BaiduConfig.applicationNotiyReturnUrl,"gbk");
	 //商户自定义数据
	 //   String tempextra=request.getParameter("extra");
	   // String extra ="extra="+tempextra;
	 //   String extra1="extra="+URLEncoder.encode(tempextra,"gbk");
	    
	    //签名串拼接数组
		String[]array={
			//	mno,
		//	 mname,
	 	     //  tno,
				
   				pay_code,
			    service_code,
				sp_no,
				order_create_time,
				order_no,
				goods_name,
			//	goods_desc,
				goods_url,
				total_amount,
				currency,
				//return_url,
				expire_time,
				input_charset,
				version,
				sign_method
			//	,extra
				};
		//浏览器参数拼接数组
		String[]array1={
			//	mno,
		 //    mname1,
	     //	 tno,
				pay_code,
			    service_code,
				sp_no,
				order_create_time,
				order_no,
				goods_name1,
			//	goods_desc1,
				goods_url1,
				total_amount,
				currency,
			//	return_url1,
				expire_time,
				input_charset,
				version,
				sign_method
				//extra1
				};
		/**
		 * 4、调用bfb_sdk_comm里create_bdpay_pay_order_url方法生成百度钱包付码接口URL
		 *   array是待签名串
		 *   array1地址栏拼接串
		 */
		String getURL=new BfbSdkComm().create_bdpay_pay_order_url(array,array1,BFB_PAY_DIRECT_O2O_PAY_URL);
		
		 /**
         * 5、向百付宝发起订单支付请求
         */
		
		
		
	    HttpClient httpClient =  new  HttpClient();    
	    httpClient.getParams().setParameter(
	    	      HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
	    // 设置 Http 连接超时为5秒    
	    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 5000 );   
	     /* 生成 GetMethod 对象并设置参数 */    
	    GetMethod getMethod =  new  GetMethod(getURL);    
	     // 设置 get 请求超时为 5 秒    
	    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,  5000 );   
	      // 设置请求重试处理，用的是默认的重试处理：请求三次    
	    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new  DefaultHttpMethodRetryHandler());         
	    String responseStr = "" ;    
	     /**
	      * 6、 执行 HTTP GET 请求
	      */ 
	     try  
	     {    
	         int  statusCode = httpClient.executeMethod(getMethod); 
	         /*  判断访问的状态码 */    
	         if  (statusCode != HttpStatus.SC_OK) 
	         {    
	            System.out.println( "HttpStatus.SC_OK :" + getMethod.getStatusLine());   
	          }    
	      
	        // HTTP响应头部信息，这里简单打印                 	         
	        // 读取 HTTP 响应内容，这里简单打印网页内容    
           
            InputStream ins = getMethod.getResponseBodyAsStream();
            

          BufferedReader br = new BufferedReader(new InputStreamReader(ins,"GBK"));
          StringBuffer sbf = new StringBuffer();
          String line = null;
          while ((line = br.readLine()) != null)
          {
          sbf.append(line);
          }

          br.close();
           
            
          String   result = sbf.toString();
            System.out.println( "getMethod.getResponseBodyAsString()返回的json原文:" +result+"json原文返回值"+"<br/>");
            JSONObject resjson=null;
            try{
                  resjson = JSONObject.parseObject(result);
             }catch(Exception e ){
            	 
             	resultStr=result;
             	return resultStr;
             }
            String ret = resjson.getString("ret");
            if(ret.equals("0")){
            JSONObject data=resjson.getJSONObject("content");
            String baifubaoSign = data.getString("sign");
            String verifySign = new BfbSdkComm().verify_CodePay_sign(resjson);
          
       
    		
            System.out.println("返回数据           :" + result + "<br/>  ");	
            System.out.println("本地签名串            :" + verifySign + "本地签名串<br/>  ");
            System.out.println("百付宝返回签名串:" + baifubaoSign + "百付宝返回签名串<br/> " );
            System.out.println( "本地签名串           : " + verifySign + "本地签名串  \n\r");
            System.out.println("百付宝返回签名串: " + baifubaoSign + "百付宝返回签名串" );
	    	   if(verifySign.equalsIgnoreCase(baifubaoSign))
	    	   {
	    		   System.out.println("验证签名通过 <br/>  ");
	    		   System.out.println( "验证签名通过\n\r  ");
	    		   resultStr=result;
	    	   }else 
	    	   {
	    		   System.out.println("验证签名失败 <br/>  ");
	    		    System.out.println("请求异常，请检查httpClient\n\r" );
	    	   }
            }else{
            	 System.out.println("返回数据           :" + result + "<br/>  ");	
            	resultStr=result;
            }
	 
	      }catch (HttpException e) {    
	         // 发生致命的异常，可能是协议不对或者返回的内容有问题   
	    	  System.out.println( "HttpException异常" );   
	    	  System.out.println( "HttpException异常，请检查代码" );
	      } 
	      finally  
	      {    
	         /* 释放连接 */    
	    	  getMethod.releaseConnection();    
	      }    
		
		//在日志里面打印提交串
	     System.out.println( "百度钱包付码 getURL提交地址：："+getURL);
		//打印完成关闭日志
 	
 		return resultStr;
	}
    
	public String getServletInfo() {
		return "O2o_CodePayServlet";
	}
	public void init(ServletConfig config) throws ServletException {
		scon = config;
	}

}
